import * as $progress from '@/api/progress'
import * as _helper from '@/utils/helper'
import dayjs from 'dayjs'

import {SET_DOCUMENT, DOCUMENT_RESET_DOCUMENTS_UNREAD_COUNT} from './document'
import {ANSWER_SET_ANSWERS} from './answer'
import {TASK_RESET_TASK_UNREAD_COUNT, TASK_RESET_TASKS_UNREAD_COUNT, TASK_RESET_TASK_PROGRESSES_UNREAD_COUNT, TASK_UPDATE_TASK_PROGRESSES_LIKED} from './task'

export const SET_PROGRESS = 'SET_PROGRESS'
export const UPDATE_IS_SHOW_REPLY_FORM = 'UPDATE_IS_SHOW_REPLY_FORM'
export const PROGRESS_UPDATE_PAGE_ROLE = 'PROGRESS_UPDATE_PAGE_ROLE'
export const PROGRESS_UPDATE_LIKED = 'PROGRESS_UPDATE_LIKED'
export const PROGRESS_SET_PROGRESSES = 'PROGRESS_SET_PROGRESSES'
export const PROGRESS_RESET_PROGRESSES = 'PROGRESS_RESET_PROGRESSES'
export const PROGRESS_RESET_PROGRESSES_UNREAD_COUNT = 'PROGRESS_RESET_PROGRESSES_UNREAD_COUNT'
export const PROGRESS_REST_TASK_PROGRESSES_UNREAD_COUNT = 'PROGRESS_REST_TASK_PROGRESSES_UNREAD_COUNT'
export const PROGRESS_UPDATE_PROGRESSES_STATE = 'PROGRESS_UPDATE_PROGRESSES_STATE'
export const PROGRESS_SET_PAGE_TASK_ID = 'PROGRESS_SET_PAGE_TASK_ID'
export const PROGRESS_SET_PAGE_PROGRESS_ID = 'PROGRESS_SET_PAGE_PROGRESS_ID'
export const PROGRESS_UPLOADING_MEDIA_NUM = 'PROGRESS_UPLOADING_MEDIA_NUM'
export const PROGRESS_SET_PAGE_PROGRESSES_LOADED = 'PROGRESS_SET_PAGE_PROGRESSES_LOADED'

export const PROGRESS_UPDATE_TEXT_BLOCKS = 'PROGRESS_UPDATE_TEXT_BLOCKS'
export const PROGRESS_RESET_TEXT_BLOCKS = 'PROGRESS_RESET_TEXT_BLOCKS'
export const PROGRESS_SET_MEDIA_BLOCKS = 'PROGRESS_SET_MEDIA_BLOCKS'
export const PROGRESS_SET_UPLOAD_QUEUES = 'PROGRESS_SET_UPLOAD_QUEUES'
export const PROGRESS_SET_UPLOAD_QUEUE = 'PROGRESS_SET_UPLOAD_QUEUE'
export const PROGRESS_SET_TEXT_BLOCK_VALUE = 'PROGRESS_SET_TEXT_BLOCK_VALUE'

export const PROGRESS_SET_IS_CREATE_ABLE = 'PROGRESS_SET_IS_CREATE_ABLE'
export const PROGRESS_SET_IS_NEED_REDO = 'PROGRESS_SET_IS_NEED_REDO'
export const PROGRESS_SET_IS_FORM_OPEN = 'PROGRESS_SET_IS_FORM_OPEN'
export const PROGRESS_SET_OPEN_FROM_IDS = 'PROGRESS_SET_OPEN_FROM_IDS'

const state = {
  pageTaskId: 0,
  pageProgressId: 0,
  progress: {
    id: 0,
    user: {
      id: 0
    },
    task: {
      isExpired: true,
      expireAt: null
    },
    member: {
      name: ''
    },
    document: {
      data: {
        blocks: []
      },
      user: {
        id: 0,
        avatarUrl: '',
        nickName: ''
      }
    }
  },
  progresses: [],
  pageRole: '',
  pageProgressesLoaded: false,
  isShowReplyForm: false,
  textBlocks: {},
  textBlockValue: '',
  mediaBlocks: {},
  uploadQueues: {},
  uploadQueue: [],
  isCreateAble: false,
  isNeedRedo: false,
  openFormIds: []
}

const getters = {
  progress: state => state.progress,
  pageTaskId: state => state.pageTaskId,
  openFormIds: state => state.openFormIds,
  pageProgressId: state => state.pageProgressId,
  textBlocks: state => state.textBlocks,
  isFormOpen: state => state.isFormOpen,
  textBlockValue: state => state.textBlockValue,
  uploadQueue: state => state.uploadQueue,
  uploadQueues: state => state.uploadQueues,
  mediaBlocks: state => state.mediaBlocks,
  isNeedRedo: state => state.isNeedRedo,
  pageProgressesLoaded: state => state.pageProgressesLoaded,
  progresses (state) {
    let t = []
    state.progresses.forEach(n => {
      let createdAtName = _helper.timeName(n.createdAt)
      n.createdAtName = createdAtName
      let expireAtName = ''
      if (n.task && n.task.expireAt) {
        n.task.expireAtName = _helper.timeName(n.task.expireAt)
      }
      t.push(n)
    })
    return t
  },
  isShowReplyForm: state => state.isShowReplyForm,
  pageRole (state, getters, rootState, rootGetters) {
    if (!rootState.auth.loginer.id) return ''
    if (!state.progress.id) return ''
    if (!state.progress.document || !state.progress.document.user || !state.progress.document.user.id) return ''
    let currentUserId = rootState.auth.loginer.id
    let progressOwnerId = parseInt(state.progress.user.id)
    let documentOwnerId = parseInt(state.progress.document.user.id)
    if (currentUserId * progressOwnerId * documentOwnerId === 0) return ''
    if (currentUserId === progressOwnerId) return 'progress-owner'
    if (currentUserId === documentOwnerId) return 'document-owner'
    return 'customer'
  },
  isCreateAble: state => state.isCreateAble,
}

const actions = {
  async createByDid ({ dispatch, commit, state, rootState }, { documentId, groupId, distributeAt = '' }) {
    let res = await $progress.createByDid({documentId, groupId, distributeAt})
    commit(SET_PROGRESS, res)
    return res
  },
  async createByTaskId ({ dispatch, commit, state, rootState }, taskId) {
    dispatch('updateIsLoading', true, {root: true})
    let res = await $progress.createByTaskId(taskId)
    dispatch('updateIsLoading', false, {root: true})
    commit(SET_PROGRESS, res)
    return res
  },
  setPageProgressesLoaded ({ commit, state, rootState }, flag) {
    commit(PROGRESS_SET_PAGE_PROGRESSES_LOADED, flag)
  },
  async fetchById ({ dispatch, commit, state, rootState }, {progressId, cache = true}) {
    let res = await $progress.getById({progressId, cache})
    commit(SET_PROGRESS, res)
    commit('document/' + SET_DOCUMENT, res.document, {root: true})
    commit('answer/' + ANSWER_SET_ANSWERS, res.answers, {root: true})
  },
  async read ({ dispatch, commit, state, rootState }, progressId) {
    let t = await $progress.read(progressId)
    commit('document/' + DOCUMENT_RESET_DOCUMENTS_UNREAD_COUNT, {documentId: t.document.id, unreadCount: t.document.unreadCount}, {root: true})
    commit('task/' + TASK_RESET_TASKS_UNREAD_COUNT, rootState.task.task.id, {root: true})
    if (state.progresses.length > 0) {
      commit(PROGRESS_RESET_PROGRESSES_UNREAD_COUNT, progressId)
    }
    commit('task/' + TASK_RESET_TASK_PROGRESSES_UNREAD_COUNT, progressId, {root: true})
  },
  updateIsShowReplyForm ({ dispatch, commit, state, rootState }, flag) {
    commit(UPDATE_IS_SHOW_REPLY_FORM, flag)
  },
  updateTextBlocks ({ dispatch, commit, state, rootState }, {progressId, value}) {
    commit(PROGRESS_UPDATE_TEXT_BLOCKS, {progressId, value})
  },
  resetTextBlocks ({ dispatch, commit, state, rootState }, progressId) {
    commit(PROGRESS_RESET_TEXT_BLOCKS, progressId)
  },
  setPageTaskId ({ dispatch, commit, state, rootState }, taskId) {
    commit(PROGRESS_SET_PAGE_TASK_ID, taskId)
  },
  setIsNeedRedo ({ dispatch, commit, state, rootState }, flag) {
    commit(PROGRESS_SET_IS_NEED_REDO, flag)
  },
  setIsFormOpen ({ dispatch, commit, state, rootState }, flag) {
    commit(PROGRESS_SET_IS_FORM_OPEN, flag)
  },
  addToOpenFormIds ({ dispatch, commit, state, rootState }, id) {
    let openFormIds = state.openFormIds
    openFormIds.push(id)
    commit(PROGRESS_SET_OPEN_FROM_IDS, openFormIds)
  },
  removeFromOpenFormIds ({ dispatch, commit, state, rootState }, id) {
    let openFormIds = []
    state.openFormIds.forEach(n => {
      if (n === id) return
      openFormIds.push(n)
    })
    commit(PROGRESS_SET_OPEN_FROM_IDS, openFormIds)
  },
  setPageProgressId ({ dispatch, commit, state, rootState }, progressId) {
    commit(PROGRESS_SET_PAGE_PROGRESS_ID, progressId)
  },
  star ({ dispatch, commit, state, rootState }) {
    $progress.createRating(state.progress.id)
    commit(PROGRESS_UPDATE_LIKED, true)
    commit('task/' + TASK_UPDATE_TASK_PROGRESSES_LIKED, {progressId: state.progress.id, flag: true}, {root: true})
  },
  unstar ({ dispatch, commit, state, rootState }) {
    $progress.removeRating(state.progress.id)
    commit(PROGRESS_UPDATE_LIKED, false)
    commit('task/' + TASK_UPDATE_TASK_PROGRESSES_LIKED, {progressId: state.progress.id, flag: false}, {root: true})
  },
  setMediaBlocks ({ commit, state, rootState }, {progressId, blocks}) {
    commit(PROGRESS_SET_MEDIA_BLOCKS, {progressId, blocks})
  },
  setUploadQueues ({ commit, state, rootState }, {progressId, uploadQueue}) {
    commit(PROGRESS_SET_UPLOAD_QUEUES, {progressId, uploadQueue})
  },
  getIsCreateAble ({ commit, state, rootState }) {
    let uploadingMediaNum = rootState.ui.uploadingMediaNum
    if (uploadingMediaNum > 0) {
      commit(PROGRESS_SET_IS_CREATE_ABLE, false)
      return
    }
    let pageProgressId = state.pageProgressId
    let textBlocks = state.textBlocks
    let contentBlock = textBlocks[pageProgressId] || {value: ''}
    let mediaBlocks = state.mediaBlocks

    let blocks = mediaBlocks[pageProgressId] || []

    if ((!contentBlock.value && blocks.length === 0) || uploadingMediaNum > 0) {
      commit(PROGRESS_SET_IS_CREATE_ABLE, false)
      return
    }
    commit(PROGRESS_SET_IS_CREATE_ABLE, true)
  },
  setTextBlockValue ({ commit, state, rootState }) {
    if (!state.pageProgressId) {
      commit(PROGRESS_SET_TEXT_BLOCK_VALUE, '')
      return
    }
    if (!state.textBlocks[state.pageProgressId]) {
      commit(PROGRESS_SET_TEXT_BLOCK_VALUE, '')
      return
    }
    commit(PROGRESS_SET_TEXT_BLOCK_VALUE, state.textBlocks[state.pageProgressId].value)
  },
}

const mutations = {
  PROGRESS_SET_PAGE_TASK_ID (state, taskId) {
    state.pageTaskId = taskId
  },
  PROGRESS_SET_PAGE_PROGRESSES_LOADED (state, flag) {
    state.pageProgressesLoaded = flag
  },
  PROGRESS_SET_PAGE_PROGRESS_ID (state, progressId) {
    state.pageProgressId = progressId
  },
  PROGRESS_RESET_PROGRESSES_UNREAD_COUNT (state, progressId) {
    let idx = -1
    state.progresses.forEach((n, i) => {
      if (n.id === progressId) idx = i
    })
    if (idx === -1) return
    state.progresses[idx].unreadCount = 0
  },
  SET_PROGRESS (state, progress) {
    state.progress = progress
  },
  PROGRESS_UPDATE_TEXT_BLOCKS (state, {progressId, value}) {
    let t = state.textBlocks[progressId] || {
      id: _helper.genCmptNo(progressId),
      type: 'text',
      value: ''
    }
    t.value = value
    state.textBlockValue = value
    state.textBlocks[progressId] = t
  },
  PROGRESS_RESET_TEXT_BLOCKS (state, progressId) {
    if (state.textBlocks[progressId]) {
      state.textBlocks[progressId].value = ''
    }
  },
  PROGRESS_RESET_PROGRESSES (state, progresses) {
    state.progresses = progresses
  },
  PROGRESS_UPDATE_LIKED (state, flag) {
    state.progress.liked = flag
  },
  UPDATE_IS_SHOW_REPLY_FORM (state, flag) {
    state.isShowReplyForm = flag
  },
  PROGRESS_SET_PROGRESSES (state, progresses) {
    state.progresses = [...state.progresses, ...progresses]
  },
  PROGRESS_SET_MEDIA_BLOCKS (state, {progressId, blocks}) {
    state.mediaBlocks[progressId] = blocks
  },
  PROGRESS_SET_UPLOAD_QUEUES (state, {progressId, uploadQueue}) {
    state.uploadQueues[progressId] = uploadQueue
  },
  PROGRESS_SET_UPLOAD_QUEUE (state, queue) {
    state.uploadQueue = queue
  },
  PROGRESS_SET_IS_CREATE_ABLE (state, flag) {
    state.isCreateAble = flag
  },
  PROGRESS_REST_TASK_PROGRESSES_UNREAD_COUNT (state, progressId) {
    let t = []
    state.progresses.forEach(n => {
      if (n.id === progressId) {
        n.unreadCount = 0
      }
      t.push(n)
    })
    state.progresse = t
  },
  PROGRESS_UPDATE_PROGRESSES_STATE (state, { progressId, st }) {
    let t = []
    state.progresses.forEach(n => {
      if (n.id === progressId) {
        n.state = st
      }
      t.push(n)
    })
    state.progresse = t
  },
  PROGRESS_SET_TEXT_BLOCK_VALUE (state, value) {
    state.textBlockValue = value
  },
  PROGRESS_SET_IS_NEED_REDO (state, value) {
    state.isNeedRedo = value
  },
  PROGRESS_SET_IS_FORM_OPEN (state, value) {
    state.isFormOpen = value
  },
  PROGRESS_SET_OPEN_FROM_IDS (state, value) {
    state.openFormIds = value
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
